#!/bin/bash

# This script is used to execute prereleae and production deployments.
# It should be run from the infrastructure machine.
# The script is saved in git repository so that we can track changes to it.
# If the script is updated, upload a new copy to the infrastructure machine
# to /home/ansible.

function usage() {
  echo "Usage: $0 [Version] [ansible_args]"
  echo "  version: The version of tripleA we will deploy eg: 1.10.5252"
  echo "  ansible_args: Args passed to ansible-playbook"
  echo "Example: $0 1.10.5252 -i ansible/inventory/prerelease"
  echo "Example: $0 1.10.5252 --diff -v -i ansible/inventory/prerelease"
  exit 1
}

if [ "$#" -lt 2 ]; then
  usage
fi

export VERSION=${1-}
shift

VAULT_PASSWORD_FILE="vault_password"
if [ ! -f "$VAULT_PASSWORD_FILE" ]; then
  echo "Error: $VAULT_PASSWORD_FILE must exist"
  exit 1
fi

HTTP_SERVER_JAR="ansible/roles/http_server/files/triplea-http-server-$VERSION.jar"
if [ ! -f "$HTTP_SERVER_JAR" ]; then
  echo "Error: File does not exist: $HTTP_SERVER_JAR"
  exit 1
fi

BOT_JAR="ansible/roles/bot/files/triplea-game-headless-$VERSION.jar"
if [ ! -f "$BOT_JAR" ]; then
  echo "Error: File does not exist: $BOT_JAR"
  exit 1
fi

MIGRATIONS_ZIP="ansible/roles/flyway/files/migrations.zip"
if [ ! -f "$MIGRATIONS_ZIP" ]; then
  echo "Error: File does not exist: $MIGRATIONS_ZIP"
  exit 1
fi

ansible-vault view --vault-password-file="$VAULT_PASSWORD_FILE" ansible_ssh_key.ed25519 | ssh-add -

ansible-playbook \
  --vault-password-file "$VAULT_PASSWORD_FILE" \
 "$@" \
 ansible/site.yml
